var vpnAllocation = {},
    vpnServers = {},
  vpnModel = require('../db/models/vpn'),
  sandbox = require('./sandbox');
sandbox.on(sandbox.MSG.VPN_ASSIGNED, assigned);
sandbox.on(sandbox.MSG.VPN_ADDED, added);
sandbox.on(sandbox.MSG.VPN_REMOVED, removed);
sandbox.on(sandbox.MSG.VPN_RESET, reset);
/**
 * 初始化vpn分配表, app启动时调用
 */
function init() {
  return vpnModel.find().then(function(vpns) {
    vpnServers = vpns;

    // 重置
    vpnAllocation = {};
    for (var i = 0; i < vpns.length; i++) {
      vpnAllocation[vpns[i].host] = [];
    }
  });
}

function getVpnObjByHost(host) {
  for(var i = 0; i < vpnServers.length; i++) {
    if (vpnServers[i].host == host) return vpnServers[i];
  }
}
function getVpnAllocation() {
  return vpnAllocation;
}

function setVpnAllocation(host, openid) {
  if (vpnAllocation[host]) {
    vpnAllocation[host].push(openid)
  } else {
    vpnAllocation[host] = [openid];
  }
}

function getVpn(openid) {
  var allocatingVpn = '',
      minLength = 9999;
  Object.keys(vpnAllocation).some(function(host) {
    var openids = vpnAllocation[host];
    if (openids.indexOf(openid) != -1) {
      allocatingVpn = host;
      return true;
    }
    if (minLength >= openids.length) {
      minLength = openids.length;
      allocatingVpn = host;
    }
  });

  return getVpnObjByHost(allocatingVpn);
}

function assigned(msg) {
  if (vpnAllocation[msg.host]) vpnAllocation[msg.host].push(msg.openid);
}

/**
 * 从数据库中取得最新的vpn server信息, 并建立一个新添加host的vpn分配列表
 * @param msg
 * @returns {Request|*}
 */
function added(msg) {
  reset(msg);
}

/**
 * 从vpn分配列表和vpn server列表中删除相关vpn信息
 * @param msg
 * @returns {*|Array.<T>}
 */
function removed(msg) {
  if (vpnAllocation[msg.host]) {
    delete vpnAllocation[msg.host];

    // 从vpnServers列表中删除
    for(var i = 0; i < vpnServers.length; i++) {
      if (vpnServers[i].host == msg.host) vpnServers.splice(i, 1);
    }
  }
}

function reset(msg) {
  if (msg.host) {
    vpnAllocation[msg.host] = [];
    return vpnModel.findOne({host:msg.host}).then(function (resetHost) {
      var index = -1;

      // 如果是变更, 找到index
      for(var i = 0; i < vpnServers.length; i++) {
        if (vpnServers[i].host == resetHost.host) {
          index = i;
          break;
        }
      }

      // 变更
      if (index >= 0) {
        vpnServers[index] = resetHost;
      } else {

        // 添加
        vpnServers.push(resetHost);
      }
    });
  }
}

function getVpnServers () {
  return vpnServers;
}
module.exports = {
  init: init,
  getVpn: getVpn,
  getVpnAllocation: getVpnAllocation,
  setVpnAllocation: setVpnAllocation,
  getVpnServers: getVpnServers,
  sandbox: sandbox
};